import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import Pagination from '@/components/Pagination'
import Image from 'next/image'
import { formatDate } from '@/lib/utils'
import { useCallback, useEffect, useState } from 'react'
import { videoService } from '@/services/api/video'

export interface HistoryItem {
  thumbnail: string // 缩略图 URL
  createTime: string // 生成时间
  duration: string // 视频时长
  fileSize: string // 文件大小
  url: string // 视频资源
}

interface HistoryDialogProps {
  open: boolean
  onOpenChange: (open: boolean, newUrl: string | null) => void
  createdId: string
}

const ITEMS_PER_PAGE = 5

export function MovieHistoryDialog({
  open,
  onOpenChange,
  createdId,
}: HistoryDialogProps) {
  const [currentPage, setCurrentPage] = useState(1)
  const [totalPages, setTotalPages] = useState(0)
  const [selectedHistoryIndex, setSelectedHistoryIndex] = useState<number | null>(
    null,
  )
  const [history, setHistory] = useState<HistoryItem[]>([])

  const getHistoryList = useCallback(() => {
    videoService
      .getAudioVideoHistoryList({
        id: createdId,
        pageNum: currentPage,
        pageSize: ITEMS_PER_PAGE,
      })
      .then((res) => {
        console.log('res:', res)
        const videoList: HistoryItem[] = res.data.map((item) => {
          return {
            thumbnail: item.result?.target_image_face_detect_data?.img_url || '',
            createTime: formatDate(new Date(item.created_at), '年月日'),
            // duration: '13: 24',
            // fileSize: '13MB',
            duration: item.broadcast_copy_history?.result?.data || '',
            fileSize: '',
            url: item.result?.success_data?.url || '',
          }
        })
        setHistory(videoList)
        setTotalPages(Math.ceil(res.total / ITEMS_PER_PAGE))
        setSelectedHistoryIndex(null)
      })
  }, [createdId, currentPage])

  useEffect(() => {
    if (open) {
      getHistoryList()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPage, open])

  const handleClose = () => {
    onOpenChange(false, null)
  }
  const onSelectHistory = (index: number) => {
    setSelectedHistoryIndex(index)
    const newUrl = history[index]?.url || null
    onOpenChange(false, newUrl)
  }

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>历史记录</DialogTitle>
        </DialogHeader>
        <div className="py-4 h-[600px] max-h-[75vh] overflow-y-auto my-scrollbar">
          {history.map((item, index) => (
            <div
              key={index}
              onClick={() => onSelectHistory(index)}
              className="flex items-center gap-4 p-4 border-b last:border-b-0 cursor-pointer hover:bg-gray-50"
            >
              <div className="w-16 h-16 relative flex-shrink-0">
                <Image
                  src={item.thumbnail}
                  alt="thumbnail"
                  fill
                  className="object-cover rounded"
                />
              </div>
              <div className="flex-1 min-w-0">
                <div className="text-sm">
                  <div className="flex items-center gap-2 text-gray-500">
                    <span>生成时间：</span>
                    <span>{item.createTime}</span>
                  </div>
                  <div className="flex items-center gap-2 text-gray-500 mt-1">
                    <span className="whitespace-nowrap">口播文案：</span>
                    <div className="max-h-[100px] overflow-hidden text-ellipsis line-clamp-4">
                      {item.duration}
                    </div>
                  </div>
                  {/* <div className="flex items-center gap-2 text-gray-500 mt-1">
                  <span>文件大小：</span>
                  <span>{item.fileSize}</span>
                </div> */}
                </div>
              </div>
            </div>
          ))}
          {history.length === 0 && (
            <div className="text-center text-gray-500 py-8">暂无历史记录</div>
          )}
        </div>
        {totalPages > 1 && history.length > 0 && (
          <div className="flex items-center justify-between pt-4 border-t">
            <Pagination
              className="justify-end mb-4"
              isMini={true}
              currentPage={currentPage}
              totalPages={totalPages}
              onPageChange={setCurrentPage}
            />
          </div>
        )}
      </DialogContent>
    </Dialog>
  )
}

// 使用示例：
/*
const [isOpen, setIsOpen] = useState(false)
const [currentPage, setCurrentPage] = useState(1)
const [history, setHistory] = useState<HistoryItem[]>([
  {
    thumbnail: '/path/to/thumbnail.jpg',
    createTime: '2024年11月25日',
    duration: '13: 24',
    fileSize: '13MB'
  },
  // ... more items
])

<HistoryDialog
  open={isOpen}
  onOpenChange={setIsOpen}
  history={history}
  setSelectedHistoryIndex={(index) => {
    console.log('Selected history index:', index)
  }}
/>
*/
